package teamblue.cardex.activities;


import teamblue.cardex.R;
import teamblue.cardex.components.Card;
import teamblue.cardex.components.CardexDb;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.Settings;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class CardexMain extends ListActivity {
	
	private final static int NEW_CARD=0;
	private final static int VIEW_CARD = 1;
	private final static int DELETE_CARD=2;
	private final static int UPDATE_CARD=3;
	private final static int QUIT=4;
	private final static int DELETE_DIALOG = 5;
	private final static int CANCEL = 6;
	private final static int INFO = 7;
	
	private CardexDb mDb;
	private CardAdapter mCardAdapter;
	private Cursor mCursor;
	private static long delete_candidate;
	private static String delete_name;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  //SETUP ACTIVITY
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.main);
	  mDb = new CardexDb(this).open();
	  
	  //RESET DATABASE EACH TIME
	  //mDb.reset();
	  
	  mCursor = mDb.getAllCards();
	  mCardAdapter = new CardAdapter(this, mCursor);	  
	  setListAdapter(mCardAdapter);
	  startManagingCursor(mCursor);
	  getListView().setOnItemClickListener(new OnItemClickListener(){

		public void onItemClick(AdapterView<?> arg0, View view, int position, long cardId) {
			viewCard(cardId);
		}});
	  
	  registerForContextMenu(getListView());
	  
	  
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		mDb.close();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.setHeaderTitle("Card Options");
		menu.add(0, VIEW_CARD, 0, R.string.view_card);
		menu.add(0, UPDATE_CARD, 0, R.string.update_card);
		menu.add(0, DELETE_CARD, 0, R.string.delete_card);
		menu.add(0, CANCEL, 0, R.string.cancel_button);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

		switch (item.getItemId()) {
		case VIEW_CARD:
			viewCard(info.id);
			return true;
		case UPDATE_CARD:
			updateCard(info.id);
			return true;
		case DELETE_CARD:
			delete_candidate = info.id;
			mCursor.moveToPosition(info.position);
			delete_name = mCursor.getString(mCursor.getColumnIndex(CardexDb.CARD_NAME));
			showDialog(DELETE_DIALOG);
			return true;
		case CANCEL:
			return true;
		default:
			return false;
		}
	}
	
	//MAIN MENU BUTTON POPUP
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0, NEW_CARD, 0, R.string.new_card).setIcon(android.R.drawable.ic_menu_add);
	    menu.add(0, INFO, 0, R.string.info).setIcon(android.R.drawable.ic_menu_info_details);
	    menu.add(0, QUIT, 0, R.string.exit).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
	    return true;
	}
	
	@Override
	// HANDLES MENU ITEM SELECTIONS
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case NEW_CARD:
	    	showDialog(NEW_CARD);
	        return true;
	    case INFO:
	    	Intent settingsIntent = new Intent(getApplicationContext(), CardexSettings.class);
	    	startActivity(settingsIntent);
	    	return true;
	    case QUIT:
	    	this.finish();
	        return true;
        default:
        	return false;
	    }
	}
	@Override
	public Dialog onCreateDialog(int id) {
	    switch (id) {
	    case NEW_CARD:
	    	AlertDialog store_select = new AlertDialog.Builder(this).setTitle(R.string.card_type_menu)
			.setItems(R.array.Stores, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface arg0, int position) {
					Intent newCardIntent = new Intent(getApplicationContext(), AddEditCard.class);
					newCardIntent.putExtra(AddEditCard.CARD_ACTION, AddEditCard.ADD_CARD);
					newCardIntent.putExtra(CardexDb.CARD_EDITABLE, 0);
					newCardIntent.putExtra(CardexDb.CARD_NAME, getResources().getStringArray(R.array.Stores)[position]);
					if(position == 0){
						newCardIntent.removeExtra(CardexDb.CARD_NAME);
						newCardIntent.putExtra(CardexDb.CARD_EDITABLE, 1);
					}
					newCardIntent.putExtra(CardexDb.CARD_URL, getResources().getStringArray(R.array.urls)[position]);
					newCardIntent.putExtra(CardexDb.CARD_PHONE, getResources().getStringArray(R.array.Phones)[position]);
					startActivity(newCardIntent);
				}
			})
			.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create();
	    	store_select.getListView().setFastScrollEnabled(true);
	    	return store_select;
	    case DELETE_DIALOG:
	    	return new AlertDialog.Builder(this)
	    	.setMessage(getResources().getString(R.string.delete_dialog)+" "+delete_name+"?")
	    		.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						deleteCard(delete_candidate);
						removeDialog(DELETE_DIALOG);
					}
	    		})
	    		.setNegativeButton(R.string.no, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						removeDialog(DELETE_DIALOG);
					}
	    		}).create();
	    default:
	    	return null;
	    }
	}
	
	private void viewCard(long cardId){
		Intent viewCard = new Intent(getApplicationContext(), CardView.class);
		viewCard.putExtra(CardexDb.CARD_ID, cardId);
		this.startActivityForResult(viewCard, 0);
	}
	private void updateCard(long cardId){
		Intent updateCard = new Intent(getApplicationContext(), AddEditCard.class);
		updateCard.putExtra(CardexDb.CARD_ID, cardId);
		startActivity(updateCard);
	}
	private void deleteCard(long cardId){
		mDb.removeCard(cardId);
		mCursor.requery();
	}
	
	private class CardAdapter extends CursorAdapter{
		
		public CardAdapter(Context context, Cursor cursor) {
			super(context, cursor, true);
		}
		
		@Override
    	public void bindView(View view, Context context, final Cursor cursor) {

       		final TextView name = (TextView) view.findViewById(R.id.card_list_item_card_name);
       		final TextView balance = (TextView) view.findViewById(R.id.card_list_item_balance);
       		final TextView note = (TextView) view.findViewById(R.id.card_list_item_note);
           	final ImageView icon = (ImageView) view.findViewById(R.id.card_list_item_card_icon);
           	int col_index;
           	
          
           	col_index = cursor.getColumnIndex(CardexDb.CARD_NAME);
           	name.setText(cursor.getString(col_index));
           	
           	col_index = cursor.getColumnIndex(CardexDb.CARD_EDITABLE);
           	int editable = cursor.getInt(col_index);
           	
           	col_index = cursor.getColumnIndex(CardexDb.CARD_ICON);
           	if(cursor.isNull(col_index))
           		icon.setImageResource(R.drawable.logo);
           	else Card.setIcon(cursor.getInt(col_index), icon, name.getText().toString(), editable);
           	
           	col_index = cursor.getColumnIndex(CardexDb.CARD_NOTE);
           	if(cursor.isNull(col_index)){
           		note.setText("");
           	}
           	else note.setText(cursor.getString(col_index));	
           	
           	col_index = cursor.getColumnIndex(CardexDb.CARD_BALANCE);
           	if(cursor.isNull(col_index)){
           		balance.setText("");
           	}
           	else{
           		
           		balance.setText("$" + AddEditCard.my_format.format(cursor.getDouble(col_index)));	    	
           	}
		}
		
		@Override
    	public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final LayoutInflater inflater = LayoutInflater.from(context);
    		final View view = inflater.inflate(R.layout.card_list_item, parent, false);
    		return view;
    	}
	};
	
}
